guess_pack(){
  find . -maxdepth 2 -type f -name 'build.gradle' | xargs -r awk '/applicationId/ {gsub(/"/,""); print $2}' | head -n1
}
guess_app(){
  for i in `find . -maxdepth 2 -type f -name 'build.gradle'`;do
    if egrep --quiet 'com.android.application' $i; then
      app=`dirname $i`
      app=${app##*/}
      echo $app
      break
    fi
  done
}
APP=`guess_app`
PACKAGE=`guess_pack`

dismiss(){
    <<HERE
    adb shell ime set com.wparam.nullkeyboard/.NullKeyboard
    adb shell input keyevent 111
HERE
    adb shell settings put secure show_ime_with_hard_keyboard 0
}
keyboard(){
    adb shell ime list -s -a
}

dos2ux(){
  for i in "*.kt" 'build.gradle'; do
    find . -type f -name "$i" | xargs -r dos2unix
  done
}
build(){
  gradle assembleRelease
}

debug(){
  gradle assembleDebug
  adb uninstall $PACKAGE
  adb install "$APP/build/outputs/apk/debug/$APP-debug.apk"
  adb shell pm list packages|egrep $PACKAGE
  adb shell monkey -p $PACKAGE -c android.intent.category.LAUNCHER 1
}

error(){
    set -x
    # -e for emulator
  #adb -e logcat "$PACKAGE:E" *:S
    adb -e logcat *:E
}
shutdown(){
  adb kill-server
  adb start-server
  adb remount
  ps -ef|egrep adb|egrep -v "grep|$0"|awk '{print $2}'|xargs -r kill -9
  ps -ef|egrep emulator|egrep -v "grep|$0"|awk '{print $2}'|xargs -r kill -9
}
status(){
  ps -ef|egrep adb|egrep -v "grep|$0"
  ps -ef|egrep emulator|egrep -v "grep|$0"
}
devices(){
  avdmanager list avd
}
install(){
  set -x
  adb uninstall $PACKAGE
  adb install "$APP/build/outputs/apk/debug/$APP-debug.apk"
  adb shell pm list packages|egrep $PACKAGE
}

uninstall(){
  adb uninstall $PACKAGE
}

refresh(){
    avdmanager delete avd -n $USER
    avdmanager create avd -n $USER -k 'system-images;android-R;google_apis;x86'
}

boot(){
  nohup $HOME/android-sdk/emulator/emulator -avd $USER &
}
launch(){
    adb shell input keyevent 4
  adb shell monkey -p $PACKAGE -c android.intent.category.LAUNCHER 1
}
preview(){
  #file='.CalendarActivity'
  file='com.kizitonwose.calendarviewsample.HomeActivity'
  #file='.InsertActivity'
  adb shell am start -n $PACKAGE/$file
}

publish(){
  ./gradlew assembleRelease
  #docker cp /home/iwill/Desktop/dist 9b:/var/www/htdocs/phpnotes/
  #sudo cp -rf /home/iwill/Desktop/dist /srv/http/phpnotes/
  sudo cp -rf ./$APP/build/outputs/apk/release /srv/http/phpnotes/dist/

  sudo systemctl restart httpd.service
  #xdg-open http://localhost/phpnotes/qrcode.php &

  timestamp=`date +"%s"`
  xdg-open http://localhost/phpnotes/images/$APP-release.png?t=$timestamp &
}
artifact(){
  ./gradlew clean assembleRelease
}

fix_usb(){
  device_id=`system_profiler SPUSBDataType 2>/dev/null \
    | awk '/^[[:blank:]]*Vendor ID/ {print $3; exit}'`
      ini=~/.android/adb_usb.ini
      if ! grep -q $device_id $ini; then
        cat >> $ini <<EOF
1
$device_id
EOF
      fi
  cat $ini
  adb kill-server
  sleep 2
  adb start-server
  sleep 2
  adb devices
}

if [[ ! $1 ]]; then
  echo [Usage] $@ xxx
  exit -1
fi

$@


